﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

namespace VSWClient.Utility
{
    public class JsonHelper
    {
        /// <summary>
        /// Serialize objects to json format
        /// </summary>
        /// <param name="o">object</param>
        /// <returns>json string</returns>
        public static string SerializeObject(object o)
        {
            string json = JsonConvert.SerializeObject(o);
            return json;
        }

        /// <summary>
        /// parse JSON string to generate object entity
        /// </summary>
        /// <typeparam name="T">object type</typeparam>
        /// <param name="json">json string(eg.{"ID":"112","Name":"石子儿"})</param>
        /// <returns>object entity</returns>
        public static T DeserializeJsonToObject<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
            T t = o as T;
            return t;
        }

        /// <summary>
        /// parse JSON array to generate object entity collection
        /// </summary>
        /// <typeparam name="T">object type</typeparam>
        /// <param name="json">json array string(eg.[{"ID":"112","Name":"NPC"}])</param>
        /// <returns>object entity collection</returns>
        public static List<T> DeserializeJsonToList<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        }

        /// <summary>
        /// deserialize json to given anonymous object
        /// </summary>
        /// <typeparam name="T">anonymous object type</typeparam>
        /// <param name="json">json string</param>
        /// <param name="anonymousTypeObject">anonymous object</param>
        /// <returns>anonymous object</returns>
        public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
        {
            T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
            return t;
        }
    }
}
